package com.DHH.Controller.Api;

import com.DHH.Config.ApiConstant;
import com.DHH.Config.Constant;

import com.DHH.Dto.*;
import com.DHH.Entity.Base.BaseLoginRecord;
import com.DHH.Entity.Base.BaseThirdpartyLogin;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Entity.Base.BaseUserInfo;
import com.DHH.Entity.Capital.CapitalSecurityGivebackRecord;
import com.DHH.Entity.Device.BikeLatest;
import com.DHH.Entity.Identity.IdentityAuthentication;
import com.DHH.Entity.Order.OrderInfo;
import com.DHH.Mapper.Api.ApiBaseUserMapper;
import com.DHH.Mapper.Api.Identity.ApiIdentityAuthenticationMapper;
import com.DHH.Mapper.Api.Order.ApiOrderInfoMapper;
import com.DHH.Mapper.Base.BaseThirdpartyLoginMapper;

import com.DHH.Mapper.Base.BaseUserInfoMapper;
import com.DHH.Mapper.Base.BaseUserMapper;
import com.DHH.Mapper.Capital.CapitalSecurityGivebackRecordMapper;
import com.DHH.Mapper.Device.BikeLatestMapper;
import com.DHH.Service.Api.ApiIdentityAuthServices;
import com.DHH.Service.Api.ApiOrderServices;
import com.DHH.Service.Base.IBaseLoginRecordService;
import com.DHH.Service.Base.IBaseUserService;
import com.DHH.Util.Http;
import com.DHH.Util.MyUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.midi.Soundbank;
import javax.validation.Valid;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 汪玉东 on 2017/8/4.
 */
@Controller
@RequestMapping("/api/user/")
public class UserApiController {
//    @Resource
//    private BaseUserController baseUserController;

    @Autowired
    private IBaseLoginRecordService baseLoginRecordService;
    @Autowired
    private ApiIdentityAuthServices apiIdentityAuthServices;
    @Resource
    private IBaseUserService baseUserService;
    @Resource
    private ApiBaseUserMapper apiBaseUserMapper;
    @Resource
    private BaseUserInfoMapper baseUserInfoMapper;
    @Resource
    private BaseThirdpartyLoginMapper baseThirdpartyLoginMapper;
    @Resource
    private CapitalSecurityGivebackRecordMapper capitalSecurityGivebackRecordMapper;
    @Resource
    private BikeLatestMapper bikeLatestMapper;

    @Resource
    private BaseUserMapper baseUserMapper;
    @Resource
    private ApiIdentityAuthenticationMapper apiIdentityAuthenticationMapper;

    @Resource
    private ApiOrderServices apiOrderServices;

    @Resource
    private ApiOrderInfoMapper  apiOrderInfoMapper;


    @RequestMapping("getUserStatus")
    @ResponseBody
    public ApiBikeMessage getUserStatus(HttpSession session){
        ApiBikeMessage message=new ApiBikeMessage();
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        if(baseUser==null){
            message.setStatus(-3);
            message.setMessage("登录失效");
            return  message;
        }

       // baseUser=baseUserMapper.selectBaseUserById(baseUser);

        if(baseUser.getPhone()==null||baseUser.getPhone().length()<=1){
            System.out.println(baseUser);
            message.setStatus(-6);
            message.setMessage("手机未绑定");
            return  message;
        }

        BaseUserInfo   baseUserInfo=new BaseUserInfo();
        baseUserInfo.setUserId(baseUser.getId());

        baseUserInfo=baseUserInfoMapper.selectOne(baseUserInfo);
        baseUser.setBaseUserInfo(baseUserInfo);
        //session.setAttribute(Constant.USER_IDENTIFICATION,baseUser);
        if(baseUserInfo.getSecurityMoney()==null||baseUserInfo.getSecurityMoney()<ApiConstant.WX_S_MONEY){
            message.setStatus(-1);
            message.setMessage("未缴纳押金");
            return  message;
        }
        Map map1=new HashMap();
        map1.put("userId",baseUser.getId());
        map1.put("state","yrz");


        IdentityAuthentication identityAuthentication=apiIdentityAuthenticationMapper.selectIdentityAuthenticationByState(map1);
        if(identityAuthentication==null||identityAuthentication.getId()==null){
            message.setStatus(-2);
            message.setMessage("未认证");
            return  message;
        }
        Map map=new HashMap();
        map.put("userId",baseUser.getId());
        map.put("state1","ddwc");
        map.put("state2","ddwc");
        OrderInfo orderInfo=apiOrderInfoMapper.selectApiOrderInfoByUserAndState(map);
        CyclingStatusResult cyclingStatusResult=new CyclingStatusResult();
        if(orderInfo!=null&&orderInfo.getStateId()==3){
            BikeLatest bikeLatest=new BikeLatest();
            bikeLatest.setUdid(orderInfo.getDeviceId());
            bikeLatest=bikeLatestMapper.selectOne(bikeLatest);
            cyclingStatusResult.setRiding_status(1);
            cyclingStatusResult.setSerial_no(orderInfo.getId().toString());
            cyclingStatusResult.setBegintimestamp(orderInfo.getStartTime().getTime()/1000);
            cyclingStatusResult.setDid(orderInfo.getDeviceId());
            cyclingStatusResult.setPercent(bikeLatest.getPercent());
            message.setMessage("有未结算的订单");
            message.setStatus(-5);
            message.setResult(cyclingStatusResult);
            return  message;
        }
        if(orderInfo!=null&&orderInfo.getStateId()==2){
            BikeLatest bikeLatest=new BikeLatest();
            bikeLatest.setUdid(orderInfo.getDeviceId());
            bikeLatest=bikeLatestMapper.selectOne(bikeLatest);
            cyclingStatusResult.setRiding_status(2);
            cyclingStatusResult.setSerial_no(orderInfo.getId().toString());
            cyclingStatusResult.setBegintimestamp(orderInfo.getStartTime().getTime()/1000);
            cyclingStatusResult.setDid(orderInfo.getDeviceId());
            cyclingStatusResult.setPercent(bikeLatest.getPercent());
            message.setMessage("有临时停车的订单");
            message.setStatus(-7);
            message.setResult(cyclingStatusResult);
            return  message;
        }

        if(orderInfo!=null&&orderInfo.getId()!=null){
            message.setStatus(1);
            message.setMessage("正在骑行中");
            return  message;
        }
        message.setStatus(0);
        message.setMessage("ok");
        return  message;
    }





    @RequestMapping("bindPhone")
    @ResponseBody
    public ApiBikeMessage update(String mobile, String code, HttpSession session){
        ApiBikeMessage message=new ApiBikeMessage();
        if(code==null||code.isEmpty()){
            message.setStatus(-5);
            message.setMessage("验证码不能为空");
            return  message;
        }
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        Object smsCode=session.getAttribute(ApiConstant.WX_SMS_CODE_KEY);
        if(smsCode==null){
            message.setStatus(-3);
            message.setMessage("请重新发送验证码");
            return  message;
        }
        if(!smsCode.toString().equals(code)){
            message.setStatus(-4);
            message.setMessage("验证码错误");
            return  message;
        }
        baseUser.setPhone(mobile);
        BaseUser upUser=new BaseUser();
        upUser.setId(baseUser.getId());
        upUser.setPhone(baseUser.getPhone());
        apiBaseUserMapper.updateByPrimaryKeySelective(upUser);
        session.setAttribute(Constant.USER_IDENTIFICATION,baseUser);
        ApiUserToken result=new ApiUserToken();
        result.setAccess_token(mobile);
        message.setStatus(2);
        message.setResult(result);
        message.setMessage("绑定手机成功");
        return  message;
    }



    @RequestMapping("auth")
    @ResponseBody
    public Message userAuth(@Valid  IdentityAuthentication identityAuthentication, BindingResult result,HttpSession session){


        String b3 = null;
        String b4 =null;
        try {
            b3 = new String(identityAuthentication.getRealName().getBytes("iso-8859-1"),"utf-8");
            b4 = new String(identityAuthentication.getContactAddress().getBytes("iso-8859-1"),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        identityAuthentication.setRealName(b3);
        identityAuthentication.setContactAddress(b4);
        Message msg = new Message();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            for (FieldError fe : err) {
                msg.addError(fe.getField().toString(), fe.getDefaultMessage());
            }
            return msg;
        }
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        if(baseUser==null){
            msg.setState(false);
            msg.setMsg("登录失效");
            return  msg;
        }
        Boolean flag=apiIdentityAuthServices.insert(identityAuthentication,baseUser);
        if(flag){
            msg.setState(true);
            msg.setMsg("上传资料成功待审核");
        }else{
            msg.setState(false);
            msg.setMsg("上传资料失败");
        }
        return msg;
    }


    @RequestMapping("getCyclingStatus")
    @ResponseBody
    public ApiBikeMessage userGetCyclingStatus(HttpSession session){
        ApiBikeMessage message=new ApiBikeMessage();
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        if(baseUser==null){
            message.setStatus(0);
            message.setMessage("登录失效");
            return  message;
        }
        CyclingStatusResult cyclingStatusResult=new CyclingStatusResult();
        Map map=new HashMap();
        map.put("userId",baseUser.getId());
        map.put("state1","ddwc");
        map.put("state2","ddwc");
        OrderInfo orderInfo=apiOrderInfoMapper.selectApiOrderInfoByUserAndState(map);

        if(orderInfo!=null&&orderInfo.getStateId()==3){
            BikeLatest bikeLatest=new BikeLatest();
            bikeLatest.setUdid(orderInfo.getDeviceId());
            bikeLatest=bikeLatestMapper.selectOne(bikeLatest);
            cyclingStatusResult.setRiding_status(1);
            cyclingStatusResult.setSerial_no(orderInfo.getId().toString());
            cyclingStatusResult.setBegintimestamp(orderInfo.getStartTime().getTime()/1000);
            cyclingStatusResult.setDid(orderInfo.getDeviceId());
            cyclingStatusResult.setPercent(bikeLatest.getPercent());
            message.setMessage("有未结算的订单");
            message.setStatus(-5);
            message.setResult(cyclingStatusResult);
            return  message;
        }

        if(orderInfo!=null&&orderInfo.getStateId()==2){
            BikeLatest bikeLatest=new BikeLatest();
            bikeLatest.setUdid(orderInfo.getDeviceId());
            bikeLatest=bikeLatestMapper.selectOne(bikeLatest);
            cyclingStatusResult.setRiding_status(1);
            cyclingStatusResult.setSerial_no(orderInfo.getId().toString());
            cyclingStatusResult.setBegintimestamp(orderInfo.getStartTime().getTime()/1000);
            cyclingStatusResult.setDid(orderInfo.getDeviceId());
            cyclingStatusResult.setPercent(bikeLatest.getPercent());
            message.setMessage("有临时停车的订单");
            message.setStatus(-7);
            message.setResult(cyclingStatusResult);
            return  message;
        }

        if(orderInfo!=null&&orderInfo.getId()!=null){
            BikeLatest bikeLatest=new BikeLatest();
            bikeLatest.setUdid(orderInfo.getDeviceId());
            bikeLatest=bikeLatestMapper.selectOne(bikeLatest);
            cyclingStatusResult.setRiding_status(1);
            cyclingStatusResult.setSerial_no(orderInfo.getOrderNumber());
            cyclingStatusResult.setBegintimestamp(orderInfo.getStartTime().getTime()/1000);
            cyclingStatusResult.setDid(orderInfo.getDeviceId());
            cyclingStatusResult.setPercent(bikeLatest.getPercent());
        }else{
            cyclingStatusResult.setRiding_status(0);
        }
        message.setMessage("请求成功");
        message.setStatus(1);
        message.setResult(cyclingStatusResult);
        return  message;
    }

    @RequestMapping("getbalance")
    @ResponseBody
    public ApiBikeMessage getbalance(HttpSession session){
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        if(baseUser==null){
            apiBikeMessage.setStatus(-3);
            apiBikeMessage.setMessage("登录失效");
            return  apiBikeMessage;
        }
        BaseUserInfo baseUserInfo=new BaseUserInfo();
        baseUserInfo.setUserId(baseUser.getId());
        baseUserInfo=baseUserInfoMapper.selectOne(baseUserInfo);

        apiBikeMessage.setStatus(1);
        apiBikeMessage.setMessage("sucess");
        apiBikeMessage.setSecurityMoney(Integer.toString((int)(ApiConstant.WX_S_MONEY*100)));
        apiBikeMessage.setResult(baseUserInfo);
        return  apiBikeMessage;
    }

    //押金退还
    @RequestMapping("depositRefundAdd")
    @ResponseBody
    public ApiBikeMessage depositRefundAdd(HttpSession session){
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        if(baseUser==null){
            apiBikeMessage.setStatus(-3);
            apiBikeMessage.setMessage("登录失效");
            return  apiBikeMessage;
        }
        Map map=new HashMap();
        map.put("userId",baseUser.getId());
        map.put("state1","ddwc");
        map.put("state2","ddwc");
        OrderInfo orderInfo=apiOrderInfoMapper.selectApiOrderInfoByUserAndState(map);

        if(orderInfo!=null&&orderInfo.getId()!=null){
            apiBikeMessage.setStatus(-1);
            apiBikeMessage.setMessage("提交押金申请失败[有未结算的订单]");
            return  apiBikeMessage;
        }

        CapitalSecurityGivebackRecord capitalSecurityGivebackRecord=new CapitalSecurityGivebackRecord();
        capitalSecurityGivebackRecord.setUserId(baseUser.getId());
        capitalSecurityGivebackRecord.setCreateTime(new Date());
        capitalSecurityGivebackRecord.setStateId(1);

        capitalSecurityGivebackRecordMapper.insert(capitalSecurityGivebackRecord);
        apiBikeMessage.setStatus(1);
        apiBikeMessage.setMessage("提交押金申请成功");
        return  apiBikeMessage;
    }

    //押金退还
    @RequestMapping("depositRefund")
    @ResponseBody
    public ApiBikeMessage depositRefund(CapitalSecurityGivebackRecord capitalSecurityGivebackRecord,HttpSession session){
        ApiBikeMessage apiBikeMessage=new ApiBikeMessage();
        BaseUser baseUser=(BaseUser)session.getAttribute(Constant.USER_IDENTIFICATION);
        if(baseUser==null){
            apiBikeMessage.setStatus(-3);
            apiBikeMessage.setMessage("登录失效");
            return  apiBikeMessage;
        }
        capitalSecurityGivebackRecord=capitalSecurityGivebackRecordMapper.selectByPrimaryKey(capitalSecurityGivebackRecord);
        System.out.println(capitalSecurityGivebackRecord);
        Message me=apiOrderServices.updateDepositComplete(capitalSecurityGivebackRecord,baseUser);
        if(me.isState()){
            apiBikeMessage.setStatus(1);
            apiBikeMessage.setMessage("退还成功");
        }else {
            apiBikeMessage.setStatus(-1);
            apiBikeMessage.setMessage("退还失败"+me.getMsg());
        }
        return  apiBikeMessage;
    }






}
